//
//  HomeCustomView.m
//  FD
//
//  Created by Yasin on 2018/10/12.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "HomeCustomView.h"
//view - -cell
#import "HomeCellOne.h"
#import "HomeCellTwo.h"
// 区头，假装表头
#import "HomeFakeHeaderView.h"
#import "HomeHeaderSectionView.h"//section1
#import "HomeHeaderSectionRxspView.h" //section2

//model
#import "HomeModel.h"
#import "HomeWhirligigModel.h"

#import "RBLocationManager.h" //定位工具类


@interface HomeCustomView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,
HomeFakeHeaderViewDelegate>
{
    NSString * _locationAddrss; /**10-29标记 定位地址*/
}

/**collectionView*/
@property (nonatomic, strong) UICollectionView *clv;
/**轮播图数据*/
@property (nonatomic,  strong) NSArray *whirligigArr;
/**热门推荐数据*/
@property (nonatomic,  strong) NSArray *hotScaleArr;
/**新品数据*/
@property (nonatomic,  strong) NSArray *xinShangArr;

/**fakeHeaderView*/
@property (nonatomic, strong) HomeFakeHeaderView *fakeHeaderView;

@end

@implementation HomeCustomView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
        
        [self requestLocation]; //请求定位
    }
    return self;
}
- (void)setupView {
    self.clv.frame = self.bounds;
    [self addSubview:self.clv];
}

#pragma mark - getter
- (UICollectionView *)clv {
    if (!_clv) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10); //左右间距10
        _clv = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _clv.backgroundColor = [UIColor whiteColor];
        //设置左右内边距 padding 挤他 其他的设置都没调用。
//        _clv.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        //代理
        _clv.delegate = self;
        _clv.dataSource = self;
        
        UINib *nib1 =  [UINib nibWithNibName:@"HomeCellOne" bundle:nil];
        UINib *nib2 = [UINib nibWithNibName:@"HomeCellTwo" bundle:nil];
        
        //注册cell
        [_clv registerNib:nib1 forCellWithReuseIdentifier:@"HomeCellOne"];
        [_clv registerNib:nib2 forCellWithReuseIdentifier:@"HomeCellTwo"];
        [_clv registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
        
        //注册区头
        [_clv registerClass:[HomeFakeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeFakeHeaderView"];
        
        UINib *sectionHeaerNib = [UINib nibWithNibName:@"HomeHeaderSectionView" bundle:nil];
        [_clv registerNib:sectionHeaerNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderSectionView"]; //美味上新
        
        [_clv registerNib:[UINib nibWithNibName:@"HomeHeaderSectionRxspView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderSectionRxspView"]; //热销商品
    }
    return _clv;
}

#pragma mark - 布局
#pragma mark - 设置数据并刷新
- (void)homeCustomReloadDataWithWhirligigArr:(NSArray<HomeWhirligigModel *> *)whirligigArr hotArr:(NSArray<HomeModel *> *)hotArr newGoodsArr:(NSArray<HomeModel *> *)newArr {
    self.whirligigArr = whirligigArr;
    
    self.hotScaleArr = hotArr;
    self.xinShangArr = newArr;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.clv reloadData];
    });
}


#pragma mark - 代理方法1
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (section == 0) { //第一个分区
        return 0;
    }else if (section == 1) { //第二分区
        return self.xinShangArr.count;
    }else if(section == 2){
        return self.hotScaleArr.count;
    }else{
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
   
    //section = 0 假装表头
    
    if (indexPath.section == 1) { //第一个分区 一行只显示一个item
        
        HomeCellOne *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomeCellOne class]) forIndexPath:indexPath];
        HomeModel *model = self.xinShangArr[indexPath.row];
        cell1.homeModel = model;
        return cell1;
        
    }else if(indexPath.section == 2){ //第二个分区 一行只显示HomeCellTwo.h两个item
        HomeCellTwo *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomeCellTwo class]) forIndexPath:indexPath];
        HomeModel *model2 = self.hotScaleArr[indexPath.row];
        cell2.homeModel2 = model2;
        return cell2;
        
    }else {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
        return cell;
    }
}

#pragma mark - 代理方法2
//UICollectionViewDelegate,UICollectionViewDataSource

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat screen_w = [UIScreen mainScreen].bounds.size.width;
    if (indexPath.section == 1) { //1个cell
//        return CGSizeMake(screen_w - 20, 230);
        
        //12-30图片比例4:3
        CGFloat w = screen_w - 20;
        CGFloat h = w*3/4 + 60;
        return CGSizeMake(w, h);
    }else if (indexPath.section == 2) { //2个cell
        //图片比例4:3,高度自适应。
        CGFloat kmargin = 10;
        CGFloat w = (screen_w - kmargin*3)*0.5;
//        CGFloat h = w + 26;
        return CGSizeMake(w, w);
    }else {
        return CGSizeZero;
    }
}
#pragma mark - 代理方法返回区头的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGFloat screen_w = [UIScreen mainScreen].bounds.size.width;
    if (section == 0) { //假装表头
//        return CGSizeMake(screen_w, FDScaleWidth(400)); // 固定死的430
        //来醉了
        CGFloat h = 300 + kWhirligigHeight;
        return CGSizeMake(screen_w, h);
    }else if(section ==1){
//        return CGSizeMake(screen_w, 30);
        return CGSizeMake(screen_w, 50);
    }else {
        return CGSizeMake(screen_w, 50+10); //热销商品10px灰线
    }
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) { //假装表头
            HomeFakeHeaderView *fakeHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeFakeHeaderView" forIndexPath:indexPath];
            
            self.fakeHeaderView = fakeHeaderView;
            //轮播图数据源<传的是一个model>
            fakeHeaderView.imgArr = self.whirligigArr;
            
            //设置代理
            fakeHeaderView.delegate = self;
          //定位不要了
//            if ([NSString isEmptyString:_locationAddrss]) { //没有定位到位置
////                [fakeHeaderView updateLocationAddress:@"定位中..."];
//            }else { //显示定位的位置
//                [fakeHeaderView updateLocationAddress:self->_locationAddrss];    
//            }
            
            //11-14发请求并更新数据，放到这里防止多次刷新
            [fakeHeaderView updateHomeUserNameJiFenKaQuanData];
            return fakeHeaderView;
        }else if(indexPath.section == 1){
            
            HomeHeaderSectionView *secHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderSectionView" forIndexPath:indexPath];
//            if (indexPath.section == 1) { //返回文字 "美味上新"
                secHeaderView.neiRongIv.image = [UIImage imageNamed:@"mwsxEng"];
//            }else {
//                secHeaderView.neiRongIv.image = [UIImage imageNamed:@"rxspEng"];
//            }
            return secHeaderView;
        }else {
            HomeHeaderSectionRxspView *rxspSectionHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeHeaderSectionRxspView" forIndexPath:indexPath]; //热销商品
            return rxspSectionHeaderView;
        }
    }else {
        return nil;
    }
}


#pragma 代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"section:%ld---row:%ld",indexPath.section, indexPath.row);

    //取出model
    HomeModel *selectedModel = nil;
    if (indexPath.section == 1) {  //新上
        selectedModel = self.xinShangArr[indexPath.row];
    }else if(indexPath.section == 2){ //热销商品
        selectedModel = self.hotScaleArr[indexPath.row];
    }
    
    NSLog(@"%@",selectedModel);
    
    //触发代理方法
    if ([self.delegate respondsToSelector:@selector(homeCustomViewDidSelectRowAtIndexPath:homeModel:)]) {
        [self.delegate homeCustomViewDidSelectRowAtIndexPath:indexPath homeModel:selectedModel];
    }
}



#pragma mark - 事件回调 HomeFakeHeaderViewDelegate
- (void)homeFakeHeaderViewclickLocationBtnAction {
//    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
    __weak typeof(self) weakSelf = self;
    if ([weakSelf.delegate respondsToSelector:@selector(homeCustomViewClickLocation)]) {
        [weakSelf.delegate homeCustomViewClickLocation];
    }
}

- (void)homeFakeHeaderViewclickMsgBtnAction {
    __weak typeof(self) weakSelf = self;
    if ([weakSelf.delegate respondsToSelector:@selector(homeCustomViewClickMsg)]) {
        [weakSelf.delegate homeCustomViewClickMsg];
    }
//    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
}

- (void)homeFakeHeaderViewClickWaiMaiDianCanAction {
    __weak typeof(self) weakSelf = self;
    if ([weakSelf.delegate respondsToSelector:@selector(homeCustomViewClickWaiMaiDianCan)]) {
        [weakSelf.delegate homeCustomViewClickWaiMaiDianCan];
    }
//    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
}

- (void)homeFakeHeaderViewClickYuYueAction {
    __weak typeof(self) weakSelf = self;
    if ([weakSelf.delegate respondsToSelector:@selector(homeCustomViewClickYuDing)]) {
        [weakSelf.delegate homeCustomViewClickYuDing];
    }
}

//12-30 二道贩子,把事件传递到控制器中。
- (void)homeFakeHeaderViewClickWhirligig:(NSString *)resource {
    if ([self.delegate respondsToSelector:@selector(homeCustomViewClickWhirligigWithResource:)]) {
        //12-30点击轮播图
        [self.delegate homeCustomViewClickWhirligigWithResource:resource];
    }
}

//2019-1-21点击了头像
- (void)homeFakeHeaderViewClickAvatorAction {
    if ([self.delegate respondsToSelector:@selector(homeCustomViewClickAvatorAction)]) {
        [self.delegate homeCustomViewClickAvatorAction];
    }
}


//!!!!:定位
- (void)requestLocation {
    
    //检查定位权限
//    if ([[RBLocationManager shareInstance] checkLocationPermission]) {
//
//        //获取当前定位信息
//        [[RBLocationManager shareInstance] updateLocationWithDesiredAccurancy:100 complectionBlock:^(CLLocation * _Nonnull location) {
//            FDLog(@"%@",location);
//
//            //转换为地标
//            [[RBLocationManager shareInstance] reverseGeocodeLocation:location complectionBlock:^(CLPlacemark * _Nonnull placemark) {
//                FDLog(@"%@",placemark);
//
//                //更新地址: locality:地点，位置
//                self->_locationAddrss = placemark.locality;
//                //刷新表头
//                NSIndexSet *s0 = [NSIndexSet indexSetWithIndex:0];
//                [self.clv reloadSections:s0];
//
//            } failBlock:^(NSError * _Nonnull error) {
//                FDLog(@"%@",error);
//            }];
//
//        } failureBlcok:^(NSError * _Nonnull error) {
//            FDLog(@"%@",error);
//        }];
//    }else { //请求定位权限
//        [[RBLocationManager shareInstance] requestLocationPermission];
//    }
}


#pragma mark - 12-3更新表头数据
- (void)updateHomeAvatorAndNickname {
    HomeFakeHeaderView *headerView = [[HomeFakeHeaderView alloc] init];
    [headerView updateHomeUserNameJiFenKaQuanData];
    
    [self.clv reloadData];
}


//显示隐藏小圆点
- (void)showRedDot {
    [self.fakeHeaderView showRedDotView];
}
- (void)hideRedDot {
    [self.fakeHeaderView hideRedDotView];
}

@end

